package l1j.server.server;

import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Config;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.clientpackets.C_CreateChar;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_CharVisualUpdate;
import l1j.server.server.serverpackets.S_OwnCharStatus;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.utils.collections.Lists;
import l1j.server.server.utils.Random;
import l1j.server.server.utils.SystemUtil;
import l1j.server.server.serverpackets.S_SystemMessage; //TODO 修改魚上鉤訊息by0968026609
import l1j.william.L1GameReStart;

/** 自動釣魚系統
 *
 * @author by99團隊
 */

public class FishingTimeController extends TimerTask {
	private static final Logger _log = Logger.getLogger(FishingTimeController.class.getName());
	private static FishingTimeController _instance;
	public static FishingTimeController getInstance() {
		if (_instance == null) {
			_instance = new FishingTimeController();
		}
		return _instance;
	}
	private ScheduledFuture<?> _timer;
	private static final int _time = 60000;//20秒檢查一次
	private final List<L1PcInstance> _fishingList = Lists.newArrayList();
	private static int ReStartTime ;

	private static int gaypc = 0;//opqlo 人數灌水
	public void addMember(final L1PcInstance pc) {
		if (pc == null || this._fishingList.contains(pc)) {
			return;
		}
		this._fishingList.add(pc);
	}


	//TODO 釣魚完成
	private void finishFishing(L1PcInstance pc) {
		final int chance = Random.nextInt(215) + 1;
		boolean finish = false;
		final int[] fish = { 41298, 41300, 41299, 41296, 41297, 41301, 41302, 41303, 41304, 41306,
				41307, 41305, 21051, 21052, 21053, 21054, 21055, 21056, 41252, 47104 };
		final int[] random = { 20, 40, 60, 80, 100, 110, 120, 130, 140, 145,
				150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 198, 201, 204 };
		for (int i = 0; i < fish.length; i++) {
			if (random[i] > chance) {
				this.successFishing(pc, fish[i]);
				finish = true;
				break;
			}
		}
		if (!finish) {
			pc.sendPackets(new S_SystemMessage("真可惜沒有釣到寶物下次再接再力。"));//TODO 修改魚上鉤訊息by0968026609
			if (pc.isFishingReady()) {
				this.restartFishing(pc);
			}
		}
	}

	private void fishing() {

		final int TrueAllPlayers=L1World.getInstance().getAllPlayerSize();
		//opqlo 人數灌水
		if(TrueAllPlayers <=0){
			gaypc =0;
		}else{
			if(Config.SERVERCE ==1){
				if(gaypc<250){
					gaypc++;
				}else{
					gaypc = Math.max(gaypc,(int)(TrueAllPlayers*0.7));
				}
			}else if(Config.SERVERCE == 3){
				if(gaypc<100){
					gaypc++;
				}else{
					gaypc = Math.max(gaypc,(int)(TrueAllPlayers*0.7));
				}
			}
		}
		//opqlo 人數灌水

		for (int i = 0; i < this._fishingList.size(); i++) {
			final L1PcInstance pc = this._fishingList.get(i);
			if(pc.getMapId()==5300){
				if (pc.isFishing()) { //TODO 釣魚中
					final long time = pc.getFishingTime();
					if(!pc.isFishingReady()){
						final long currentTime = System.currentTimeMillis();
						if (currentTime <= time + _time&& currentTime >= time - _time) {
							pc.setFishingReady(true);
							this.finishFishing(pc);
						}
					}
				}
			}
		}


		ReStartTime = L1GameReStart.getInstance().GetRemnant();
		//opqlo 黑盒子即時資訊
		_log.info(" 假人數:"+(gaypc+L1World.getInstance().getBogusAmount())+"人 實際："+TrueAllPlayers+" 人 釣魚："+this._fishingList.size()+" 人 新角色："+C_CreateChar.NewChar+" 人【"+ReStartTime/60+"分】\n使用記憶體： " + SystemUtil.getUsedMemoryMB() + "MB");
		//		System.out.println(L1World.getInstance().getAllVisibleObjects().size());
		//		_log.info("\n使用記憶體： " + SystemUtil.getUsedMemoryMB() + "MB");
		//		SystemUtil.printMemoryUsage(_log);

		//opqlo 黑盒子即時資訊
	}

	public int getGayPcCount(){
		return gaypc;
	}

	public void removeMember(final L1PcInstance pc) {
		if (pc == null || !this._fishingList.contains(pc)) {
			return;
		}
		this._fishingList.remove(pc);
	}

	//TODO 重新釣魚
	private void restartFishing(L1PcInstance pc) {
		if (pc.getInventory().consumeItem(41295, 1)) { //TODO 消耗餌，重新釣魚
			final long fishTime = System.currentTimeMillis() + 10000 + Random.nextInt(5) * 1000;
			pc.setFishingTime(fishTime);
			pc.setFishingReady(false);
		} else {
			pc.sendPackets(new S_SystemMessage("想要釣到寶物就需要有餌。"));//TODO 修改魚上鉤訊息by0968026609
			this.stopFishing(pc);
		}
	}
	@Override
	public void run() {
		try {

			this.fishing();

		} catch (final Exception e) {
			//			this._timer.cancel(false);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final FishingTimeController timerTask = new FishingTimeController();
			timerTask.start();
		}
	}

	public void start() {
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this, _time, _time);
	}

	//TODO 停止釣魚
	private void stopFishing(L1PcInstance pc) {
		pc.setFishingTime(0);
		pc.setFishingReady(false);
		pc.setFishing(false);
		pc.sendPackets(new S_CharVisualUpdate(pc));
		pc.broadcastPacketAll(new S_CharVisualUpdate(pc));
		FishingTimeController.getInstance().removeMember(pc);
	}

	//TODO 釣魚成功
	private void successFishing(L1PcInstance pc, int itemId) {
		final L1ItemInstance item = ItemTable.getInstance().createItem(itemId);
		if (item != null) {
			pc.sendPackets(new S_ServerMessage(403, item.getItem().getName()));
			pc.addExp(2);
			pc.sendPackets(new S_OwnCharStatus(pc));
			item.setCount(1);
			if (pc.getInventory().checkAddItem(item, 1) == L1Inventory.OK) {
				pc.getInventory().storeItem(item);
			} else { //TODO 負重過重，結束釣魚
				this.stopFishing(pc);
				item.startItemOwnerTimer(pc);
				L1World.getInstance().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(item);
				return;
			}
		} else { //TODO 結束釣魚
			pc.sendPackets(new S_SystemMessage("真可惜沒有釣到寶物下次再接再力。"));//TODO 修改魚上鉤訊息by0968026609
			this.stopFishing(pc);
			return;
		}

		if (pc.isFishingReady()) {
			if (itemId == 47104) {
				pc.sendPackets(new S_SystemMessage("釣到傳說的閃爍的鱗片，自動釣魚已停止。"));//TODO 修改魚上鉤訊息by0968026609
				this.stopFishing(pc);
				return;
			}
			this.restartFishing(pc);
		}
	}
}
